#!/bin/bash
# original filename: mirror-replace.sh
# 2020-2-10 updated, by Careone
# 自动生成、更换软件源 /etc/apt/sources.list.d/atzlinux.list

APPNAME="mirror-replace"
APPVER="0.2.1"

### HEAD ###
DEBUG=0

### defines ###
declare -i ID=1

declare -a mirror mir_desc
# 数组 mirror: 镜像网址


mirror[0]="https://mirrors.163.com"
mir_desc[0]="网易163"

mirror[1]="https://mirrors.huaweicloud.com"
mir_desc[1]="华为云"

mirror[2]="https://mirrors.aliyun.com"
mir_desc[2]="阿里云"

mirror[3]="https://mirrors.cloud.tencent.com"
mir_desc[3]="腾迅云"

mirror[4]="https://mirrors.tuna.tsinghua.edu.cn" 
mir_desc[4]="清华大学"

mirror[5]="https://mirrors.ustc.edu.cn"	
mir_desc[5]="中科大"

mirror[6]="https://ftp.sjtu.edu.cn"
mir_desc[6]="上海交大"

mirror[7]="https://mirror.bjtu.edu.cn" 
mir_desc[7]="北京交通大学"

# 已禁用： sohu debian, apt update 更新时可能报错。
#mirror[8]="https://mirrors.sohu.com"
#mir_desc[8]="搜狐"

#
cfg_file=
source_list=/etc/apt/sources.list

mir_dir=/etc/apt/sources.list.d
mir_file=atzlinux.list

#
MAKE_URL=	#optional: 0, 1
SHOW_OS_INFO=	#optional: 0, 1

URL1=
#URL2=
URL3="http://debian-cn.exaphotons.com"	#atzlinux repo

OS_INFO=os-info #filename string for OS informations
OS_INFO_LOCK="$HOME/os-info.lock"

#
#TIMESTAMP="`date --iso`_`date +'%H%M%S'`" #sample: 2020-2-10_23:59:59
TIMESTAMP="`date --iso`" #sample: 2020-2-10

#
OS_ID=		#example: debian
CODENAME=	#example: buster (debian 10)

#STR_DEBIAN_SECURITY="$URL1/debian-security/ ${CODENAME}/updates main"
STR_DEBIAN_SECURITY="$URL1/debian-security/ CODENAME/updates main"

## ------------------
# lsb_release -a
#
# No LSB modules are available.
# Distributor ID:	Debian
# Description:	Debian GNU/Linux 10 (buster)
# Release:	10
# Codename:	buster
## ------------------

#
# TODO * atzlinux 第三方源: $URL3
	_usage_cn () {
cat<<EOF
Usage: $APPNAME [option] 
  更换软件镜像源仓库。目前仅支持 debian 操作系统
  说明: 1. 需要以 sudo 或者 root 用户运行，才能正式生效
        2. 完成后，请运行 'sudo apt update' 更新软件源
        
Options: 
  -l, --list      列出支持的镜像网址
  -s, --show      查看 /etc/apt/sources.list 软件源配置文件 
  -s2  查看自定义配置文件 $mir_dir/$mir_file
  -i, --info    检测当前操作系统版本信息，并保存到文件 ~/${OS_INFO}_xxx.txt
    (主要用于 Debian 以外其它 DEB 系列 Linux 操作系统的后续开发支持)
       
  -a, --auto      自动随机选择镜像源
  -d, --disable   禁用 sources.list 文件中的全部软件仓库(谨慎使用！) 
  -e, --enable    启用 sources.list 文件中的全部软件仓库(谨慎使用！) 
    
  -1, --163       使用 163 镜像源    ${mirror[0]} 
  -hw, --huawei   使用 华为云 镜像源 ${mirror[1]} 
  -al, --aliyun   使用 阿里云 镜像源 ${mirror[2]} 
  -tc, --tencent  使用 腾迅云 镜像源 ${mirror[3]} 
  
  -ts, --tsinghua   使用 清华大学 镜像源 ${mirror[4]} 
  -us, --ustc       使用 中科大 镜像源   ${mirror[5]}
  -sj, --sjtu       使用 上海交大 镜像源 ${mirror[6]}
  -bj, --bjtu       使用 北京交大 镜像源 ${mirror[7]}
    
  -v, --version    显示版本信息并退出
  -h, --help       显示帮助信息并退出

See also:

Bugs: 
请发送缺陷报告给 Careone <emacslocale@126.com>. 

Homepage: 
https://gitee.com/careone/mirror-replace
EOF
}
#

# 0.
	_add_file_head () {
cat<<EOF
## filename: $mir_dir/$mir_file
## `date --iso` `date +'%H:%M:%S'`, auto created by $APPNAME
EOF
}

# 1.
	_add_debian_mirror () {
cat<<EOF
deb $URL1/${OS_ID}/ ${CODENAME} main non-free contrib
deb $URL1/${OS_ID}/ ${CODENAME}-updates main non-free contrib
deb $URL1/${OS_ID}/ ${CODENAME}-backports main non-free contrib
deb $URL1/${OS_ID}/ ${CODENAME}-proposed-updates main non-free contrib
deb $URL1/${OS_ID}-security/ ${CODENAME}/updates main
#
deb-src $URL1/${OS_ID}/ ${CODENAME} main non-free contrib
deb-src $URL1/${OS_ID}/ ${CODENAME}-updates main non-free contrib
deb-src $URL1/${OS_ID}/ ${CODENAME}-backports main non-free contrib       
deb-src $URL1/${OS_ID}/ ${CODENAME}-proposed-updates main non-free contrib
deb-src $URL1/${OS_ID}-security/ ${CODENAME}/updates main
EOF
}

# 3.

# deb http://debian-cn.exaphotons.com/debian buster main contrib non-free
# deb-src http://debian-cn.exaphotons.com/debian buster main contrib non-free

	_add_debian_atzlinux_mirror () {
cat<<EOF
deb $URL3/${OS_ID} ${CODENAME} main contrib non-free
deb-src $URL3/${OS_ID} ${CODENAME} main contrib non-free
EOF
}

### defines ###

### HEAD ###

### BODY ###

if which lsb_release &>/dev/null; then
  OS_ID=`lsb_release -si | tr 'A-Z' 'a-z'`
  CODENAME=`lsb_release -sc`
fi

for option in "$@"; do

    	case "$option" in

    	 -h | --help)
	   _usage_cn
	   exit 0 ;;

    	 -d | --disable)
	   echo " 禁用 sources.list 文件中的全部软件仓库...(谨慎使用！) "
	   echo "   技术说明：实际上是在以 deb 和 deb-src 开头的行，前面加上 # 和1个空格"
	  if [ -s "/etc/apt/sources.list" ]; then
	    if [ `whoami` = root ]; then
	       sed -i "/^deb/s//# deb/" /etc/apt/sources.list
	    else echo " 警告：需要以 sudo 或者 root 用户运行！" 1>&2
	      sleep 1
	      echo -e " 文件效果示例:\n" 1>&2
	      sleep 2 
	      sed "/^deb/s//# deb/" /etc/apt/sources.list
	    fi
	  fi

	  if [ "$?" = 0 ]; then
	    echo " Done."
	  fi
	  	  shift
	#exit 0
	 ;;

    	 -e | --enable)
	   echo " 启用 sources.list 文件中的全部软件仓库...(谨慎使用！) "
	   echo "   技术说明：* 实际上是去掉每行 deb 和 deb-src 前面的 # 和1个空格;"
	   echo "            * 忽略以 'deb cdrom'开头的行."
	  if [ -s "/etc/apt/sources.list" ]; then
	    if [ `whoami` = root ]; then
	       sed -i "/^# deb/s//deb/;/^deb cdrom/s//# &/" /etc/apt/sources.list
	    else echo " 警告：需要以 sudo 或者 root 用户运行！" 1>&2
	      sleep 1
	      echo -e " 文件效果示例:\n" 1>&2
	      sleep 2 
	      sed "/^# deb/s//deb/;/^deb cdrom/s//# &/" /etc/apt/sources.list
	    fi
	  fi
	  
	  if [ "$?" = 0 ]; then
	    echo " Done."
	  fi
	  shift
	#exit 0
	 ;;	
#	

    	 -s | --show)
    	   cfg_file="$source_list"
	   echo -e "  查看软件源配置文件 $cfg_file 的内容...\n"
	   
	   if [ -e "$cfg_file" ]; then
	     sleep 1
	     cat "$cfg_file"
	   else echo "  Error (E230): 找不到文件!" 1>&2
	       
	   fi
	   exit 0
		;;

    	 -s2)
    	   cfg_file="$mir_dir/$mir_file"
	   echo -e "  查看自定义软件源配置文件 $cfg_file ...\n"

	   if [ -e "$cfg_file" ]; then
	     sleep 1
	     cat "$cfg_file"
	   else echo "  Error (E231): 找不到文件!" 1>&2
	       
	   fi
	   exit 0
		;;
		
    	 -l | --list)
    	   echo "  开源软件镜像站点:"
    	   for a in "${mirror[@]}"; do
    	     let "b = ID - 1"
    	     echo -e "  $ID.\t$a \t${mir_desc[b]}"
    	     let "ID += 1"
    	   done
    	   
	exit 0 ;;

	 # 
    	 -i | --info)
	  SHOW_OS_INFO=1; shift;
	#exit 0
	 ;;
	 	
    	 -a | --auto)
    	   echo "  自动随机选择镜像源..." 1>&2
    	   sleep 1
    	   a="$RANDOM"
    	   b="${#mirror[@]}"
    	   let "c = a % b"
    	   URL1="${mirror[c]}"; MAKE_URL=1; shift
	 ;;

    	 -1 | --163)
    	   URL1="${mirror[0]}"; MAKE_URL=1; shift
	 ;;

    	 -hw | --huawei)
    	   URL1="${mirror[1]}"; MAKE_URL=1; shift
	 ;;
	 
     	 -al | --aliyun)
    	   URL1="${mirror[2]}"; MAKE_URL=1; shift
	 ;;

    	 -tc | --tencent)
    	   URL1="${mirror[3]}"; MAKE_URL=1; shift
	 ;;
	 
     	 -ts | --tsinghua) #清华
    	   URL1="${mirror[4]}"; MAKE_URL=1; shift
	 ;;
	 	 
    	 -us | --ustc) #中科大
    	   URL1="${mirror[5]}"; MAKE_URL=1; shift
	 ;;
	 
     	 -sj | --sjtu) #上海交大
    	   URL1="${mirror[6]}"; MAKE_URL=1; shift
	 ;;

    	 -bj | --bjtu) #北京交大
    	   URL1="${mirror[7]}"; MAKE_URL=1; shift
	 ;;

#
    	-v | --version)
	  echo "  $APPNAME $APPVER"
	  exit 0 ;;

    	-*)
	  echo "Unrecognized option \`$option'" 1>&2
	  exit 1 ;;	
	esac
	
done

# ---
  if [ "$SHOW_OS_INFO" = 1 ]; then
    echo "  check system informations..."
  
    if which lsb_release &>/dev/null; then
  	#TIMESTAMP=`date --iso`
  	## 如果存在 ${OS_INFO_LOCK} LOCK 文件，则执行 touch 操作，更新文件日期; 
  	#  如果不存在，则保存系统信息到文件，并创建 LOCK 文件; 
  	if [ -e "${OS_INFO_LOCK}" ]; then
    	  touch "${OS_INFO_LOCK}"; lsb_release -a
  	else
  	  lsb_release -a | tee ~/"${OS_INFO}_${TIMESTAMP}.txt"
  	  touch "${OS_INFO_LOCK}"; 
  	fi
   
    fi
  fi
  
#  
  if [ "$MAKE_URL" = 1 ]; then
    sleep 1
       case "$OS_ID" in
    	     debian)   
    	  #---------------------   
    	    if [ `whoami` = root ]; then
    	       echo "  更新自定义软件源: $mir_dir/$mir_file" 1>&2
    	        _add_file_head | tee > "$mir_dir/$mir_file"
    	        _add_debian_mirror | tee -a "$mir_dir/$mir_file"
    	        echo

    	     	# _add_debian_atzlinux_mirror | tee -a "$mir_dir/$mir_file"
    	     else
    	       echo " 警告：需要以 sudo 或者 root 用户运行！" 1>&2
    	        _add_debian_mirror
    	        echo

    	     	# _add_debian_atzlinux_mirror
   	    fi
	  
	  #---------------------

    	     	;;
    	     ubuntu | *)
    	       echo " Error: support Debian only! exit." 1>&2
    	       exit 1;
    	     ;;
    	   esac
    fi	   
    	   
### BODY ###

exit 0;
